import os
import ctypes

class C_Color(ctypes.Structure):
    _fields_ = [('r', ctypes.c_uint8),
                ('g', ctypes.c_uint8),
                ('b', ctypes.c_uint8),
                ('a', ctypes.c_uint8)]

class C_Cell(ctypes.Structure):
    _fields_ = [('genome', ctypes.c_uint * 64),
                ('color', C_Color),
                ('age', ctypes.c_uint),
                ('energy', ctypes.c_int),
                ('minerals', ctypes.c_int),
                ('rotation', ctypes.c_int),
                ('genomeIndex', ctypes.c_uint),
                ('type', ctypes.c_int),
                ('photosynthesisCount', ctypes.c_uint),
                ('mineralsCount', ctypes.c_uint),
                ('useMinerals', ctypes.c_bool)]

class C_World(ctypes.Structure):
    _fields_ = [('width', ctypes.c_uint),
                ('height', ctypes.c_uint),
                ('filename', ctypes.c_char*50),
                ('time', ctypes.c_int),
                ('dayLength', ctypes.c_int),
                ('timeDirection', ctypes.c_bool),
                ('cells', C_Cell*262657),
                ('mutationChance', ctypes.c_uint),
                ('maxEnergy', ctypes.c_uint),
                ('maxAge', ctypes.c_uint),
                ('foodMaxAge', ctypes.c_uint)]

class Cell:
    genome: list[int] = []
    energy: int
    age: int
    color: tuple[int, int, int] = (0, 0, 0)
    minerals: int
    direction: int
    type: int

class World:
    width: int
    height: int
    cells: list[Cell] = []
    file: str
    mutation_chance: int
    max_energy: int
    max_age: int
    food_max_age: int

    def __init__(self, file: str = "world.bin"):
        if(not(os.path.isfile(file))):
            raise(FileNotFoundError(file))
        self.file = file
        with open(self.file, 'rb') as f:
            rawData = C_World()
            f.readinto(rawData)
        self.width = rawData.width
        self.height = rawData.height
        self.mutation_chance = rawData.mutationChance
        self.max_age = rawData.maxAge
        self.food_max_age = rawData.foodMaxAge
        for i in rawData.cells:
            cell = Cell()
            for j in i.genome:
                cell.genome.append(j)
            cell.energy = i.energy
            cell.minerals = i.minerals
            cell.type = i.type
            cell.color = (i.color.r, i.color.g, i.color.b)
            cell.direction = i.rotation
            cell.age = i.age
            self.cells.append(cell)

    def get_cell(self, x: int, y: int) -> Cell:
        return(self.cells[(x+(self.width*y))])

    def set_cell(self, x: int, y: int, cell: Cell):
        self.cells[(x+(self.width*y))] = cell

    def save_world(self):
        pass
